package com.tianbo.elfii.client.common;

import java.io.*;
import java.sql.*;
import java.net.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.imageio.*;

import com.tianbo.elfii.client.common.ElfiiCommonUtil.FeedBackType;

/**  <pre>
     <b>类功能描述：</b><pre>
     完成 历史查询第2级 功能要求。
     </pre>
     @version 1.0.1
     @author 高伟 
*/

public class ElfiiCommonHistoryItem {

    JButton okButton;
    HistoryItemPanel historyPanel;
    JPanel itemPanel;
    JPanel slidePanel;

    int infoBgStartX0;
    int infoBgStartY0;

    int textSelectedNumber;
    int textStartX;
    int textStartY;
    int textStartMaxY;
    int textStartMinY;
    int textLineHeight;

    int clipBgStartX0;
    int clipBgStartY0;
    int slideBgStartX0;
    int slideBgStartY0;
    int slideButtonX;
    int slideButtonY;
    int slideButtonMinY;
    int slideButtonMaxY;

    String sqlTrainnerId;
    String sqlStartDate;
    String sqlEndDate;

    int dataChoiceIndex;
    int dataSqlLimitNumber=10;
    ArrayList dataList;

    JFrame mainFrame;
    ElfiiCommonRunInfo runInfo;

    public static int preDataChoiceIndex;
    public static int preSlideButtonY;
    public static int preTextStartY;

    public void setRunInfo(ElfiiCommonRunInfo runInfo){
        this.runInfo=runInfo;
        this.mainFrame=runInfo.getMainFrame();
    }

    public void clearPreSlide(){
        preSlideButtonY=0;
        preDataChoiceIndex=0;
    }

    class ItemDataType {
        String gameTitle;
        String trainningTitle;
        String trainningCategory;
        int trainningNumber;
    }

    public void setSqlItems(String sqlTrainnerId,String sqlStartDate,String sqlEndDate){
        this.sqlTrainnerId=sqlTrainnerId;
        this.sqlStartDate=sqlStartDate;
        this.sqlEndDate=sqlEndDate;
    }

    public void dealOkButton(){

        if (dataList.size()>0){
        	
        	ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
        	
            ItemDataType itemData=(ItemDataType) dataList.get(dataChoiceIndex);

            String trainningTitle = itemData.trainningTitle;

            mainFrame.getContentPane().removeAll();
            mainFrame.getContentPane().setLayout(new BorderLayout());
            ElfiiCommonHistoryResult historyResult = new ElfiiCommonHistoryResult();
            historyResult.setRunInfo(runInfo);

            historyResult.setSqlItems(sqlTrainnerId,trainningTitle,sqlStartDate,sqlEndDate);

            mainFrame.getContentPane().add(historyResult.createViewPanel(),BorderLayout.CENTER);
            mainFrame.validate();
        }
    }

    public void dealBackButton(){
        mainFrame.getContentPane().removeAll();
        ElfiiCommonHistorySum historyList = new ElfiiCommonHistorySum();
        historyList.setRunInfo(runInfo);

        JPanel p=historyList.createViewPanel();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.getContentPane().add(p,BorderLayout.CENTER);
        mainFrame.validate();
    }

    class HistoryItemPanel extends JPanel {

        BufferedImage unSelectedImage;
        BufferedImage selectedImage;
        BufferedImage slideBackgroundImage;

        BufferedImage clipBackgroundImage;

        public HistoryItemPanel() {
            File f=null;
            ItemDataType item;
            try {
                f=new File("resource-common/images/gw/gw_history_01_slide_bg.jpg");
                slideBackgroundImage=ImageIO.read(f);
                f=new File("resource-common/images/history/history_01_unselect.png");
                unSelectedImage=ImageIO.read(f);
                f=new File("resource-common/images/history/history_01_select.png");
                selectedImage=ImageIO.read(f);

                f=new File("resource-common/images/history/history_clipe_bg.png");
                clipBackgroundImage=ImageIO.read(f);

            } catch(Exception e) {System.out.print(e+"   "+f);}

            infoBgStartX0=95;
            infoBgStartY0=25;

            slideBgStartX0=infoBgStartX0+740;
            slideBgStartY0=infoBgStartY0+9;
            slideButtonMinY=slideBgStartY0+113;
            slideButtonMaxY=slideBgStartY0+402;
            slideButtonX=slideBgStartX0+25;
            slideButtonY=slideButtonMinY;

            clipBgStartX0=infoBgStartX0+10;
            clipBgStartY0=infoBgStartY0+20;

            textSelectedNumber=0;

            textLineHeight=164;
            textStartMaxY=clipBgStartY0+6;

            //-textStrings.length-9,其中的9是clip已经显示的内容，余下的内容才是需要向上移的。
            textStartMinY=0-(dataList.size()-3)*textLineHeight+textStartMaxY; 
            textStartX=clipBgStartX0;
            textStartY=textStartMaxY; 

            //-如果preSlideButtonY==0，应该作为第一次进入处理
            if (preSlideButtonY!=0){
                slideButtonY=preSlideButtonY;
                textStartY=preTextStartY;
            }
            if (preDataChoiceIndex!=0){
                dataChoiceIndex=preDataChoiceIndex;
            }

        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g ;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
            g2.setColor(Color.black);
            g2.fillRect(0,0,1020,540);
            g2.setColor(Color.white);
            g2.fillRoundRect(infoBgStartX0,slideBgStartY0+4,832,501,75,75);

            g2.setStroke(new BasicStroke(8.0f));
            g2.drawImage(slideBackgroundImage,null,slideBgStartX0,slideBgStartY0);
            g2.setStroke(new BasicStroke(7.0f));
            g2.fillOval(slideButtonX,slideButtonY-25,44,44);
            g2.setClip(clipBgStartX0,clipBgStartY0+6,730,475);

            String str;
            ItemDataType item;
            int k; 

            for (int i=0; i<dataList.size(); i++) {
                g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,28));
                g2.setColor(Color.black);
                if (dataChoiceIndex==i)
                    g2.setColor(Color.gray);
                g2.fillRoundRect(textStartX,textStartY+textLineHeight*i,725,textLineHeight-18,80,80);
                g2.setColor(Color.white);
                g2.fillOval(textStartX+12,textStartY+textLineHeight*i+12,65,65);

                item=(ItemDataType)dataList.get(i);
                //                g2.drawString(item.gameTitle,textStartX+90,textStartY+textLineHeight*i+50);  //+30是因为字体是从下向上画的
                str=item.trainningTitle.trim();
                if (str.length()>0){
                    str=str.substring(0,1)+str.substring(2,str.length()); //去掉点
                    if (str.length()<3)  //FG等，没有名称，只有代号，以后可能会有(20120803)
                        str=str+"   ";
                    k=2; 
                    if (str.startsWith("C10") || str.startsWith("K10") || str.startsWith("K11") || str.startsWith("K12"))
                        k=3;
                    g2.drawString(item.trainningCategory,textStartX+100,textStartY+textLineHeight*i+53);  
                    g2.drawString(str.substring(k,str.length()),textStartX+90,textStartY+textLineHeight*i+110);  
                    g2.setColor(Color.black);
                    g2.drawString(str.substring(0,k),textStartX+28-(k-2)*10,textStartY+textLineHeight*i+55);  
                }
                g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,42));
                g2.setColor(Color.white);
                g2.drawString(""+item.trainningNumber+"次",textStartX+580,textStartY+textLineHeight*i+100);  //+30是因为字体是从下向上画的
            }

            g2.drawImage(clipBackgroundImage,null,clipBgStartX0-10,clipBgStartY0-10);

            //-以下内容可以方便地查看每个按钮的坐标是否正确;
            //testXY();
        }
        public Dimension getPreferredSize() {
            return (new Dimension(832,537));
        }
    }

    public void createHistoryItemPanel(){

        calcHistoryData();

        historyPanel=new HistoryItemPanel();

        historyPanel.setLayout(new BorderLayout());
        historyPanel.setBackground(Color.black);
        historyPanel.setFocusable(true);
        historyPanel.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent e) {
                    dealMousePressed(e);
                }
            }
            );

        historyPanel.addMouseMotionListener(new MouseAdapter(){
                public void mouseDragged(MouseEvent e) {
                    dealMouseDragged(e);
                }
            }
            );
    }

    public JPanel createViewPanel(){

        JPanel p = new JPanel(new BorderLayout()) ;

        JButton okButton=new JButton();
        okButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dealOkButton();
                }
            });

        JButton backButton=new JButton();
        backButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                    dealBackButton();
                }
            });

        String dateStr=sqlStartDate.substring(0,4)+"/"+sqlStartDate.substring(4,6)+"/"+sqlStartDate.substring(6,8);
        JButton homeButton=runInfo.createHomeButton();
        JPanel topPanel=ElfiiCommonUtil.createTopPanel(sqlTrainnerId+"  "+dateStr,backButton,homeButton);
        JPanel bottomPanel=ElfiiCommonUtil.createBottomPanelLevelSelect(okButton);
        createHistoryItemPanel();
        p.setLayout(null);
        p.setBackground(Color.black);
        p.add(topPanel);
        topPanel.setBounds(0,0,1024,100);
        p.add(bottomPanel);
        bottomPanel.setBounds(0,668,1024,100);
        p.add(historyPanel);
        historyPanel.setBounds(0,101,1000,560);
        return p;
    }

    public void dealMouseDragged(MouseEvent e){
        int x=e.getX();
        int y=e.getY();
        if (x>slideButtonX && x<slideButtonX+50 && dataList.size()>3) {
            slideButtonY=y;
            if (slideButtonY>slideButtonMaxY)
                slideButtonY=slideButtonMaxY;
            if (slideButtonY<slideButtonMinY)
                slideButtonY=slideButtonMinY;
            textStartY=(int) (textStartMaxY-(textStartMaxY -textStartMinY)*(slideButtonY-slideButtonMinY)/(slideButtonMaxY-slideButtonMinY));

            preSlideButtonY=slideButtonY;
            preTextStartY=textStartY;

            historyPanel.repaint();
        }
    }

    public void dealMousePressed(MouseEvent e){
        int x=e.getX();
        int y=e.getY();
        //System.out.println("clicked x="+x+"   x0="+slideBgStartX0);

        if (x<slideBgStartX0) {

            for (int i=0; i<dataList.size(); i++){
                if (y>textStartY+textLineHeight*i && y<textStartY+textLineHeight*(i+1)){
                	
                	if(preDataChoiceIndex!=i){
                		dataChoiceIndex=i;
                		preDataChoiceIndex=dataChoiceIndex;
                		ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                	}
                	break;
                }
            }

            //System.out.println("labelStartY:"+labelStartY);
            historyPanel.repaint();
        }

        if (x>slideButtonX && x<slideButtonX+50  && dataList.size()>3) {
            slideButtonY=y;
            if (slideButtonY>slideButtonMaxY)
                slideButtonY=slideButtonMaxY;
            if (slideButtonY<slideButtonMinY)
                slideButtonY=slideButtonMinY;
            textStartY=(int) (textStartMaxY-(textStartMaxY -textStartMinY)*(slideButtonY-slideButtonMinY)/(slideButtonMaxY-slideButtonMinY));
            //System.out.println("clicked textStartY:"+textStartY);

            preSlideButtonY=slideButtonY;
            preTextStartY=textStartY;

            historyPanel.repaint();
        }
    }

    public void calcHistoryData(){
        Statement st ;
        ResultSet rs ;
        dataList=new ArrayList();
        String str="";

        String sqlStartDateHIJ=sqlStartDate.substring(0,4)+"-"+sqlStartDate.substring(4,6)+"-"+sqlStartDate.substring(6,8);
        String sqlEndDateHIJ=sqlEndDate.substring(0,4)+"-"+sqlEndDate.substring(4,6)+"-"+sqlEndDate.substring(6,8);


        //System.out.println("======HIJ "+sqlStartDateHIJ+sqlEndDateHIJ);

        try {
            long startTimeMillis=System.currentTimeMillis();
            st = runInfo.getStatement1();
            String tmpTable="tmp_"+createRandomNumber(10);
            str="create table "+tmpTable+" (trainnerID nchar(20),trainningTitle nchar(60) not null default '',trainningNumber numeric(6) not null default 0) ";
            st.execute(str);

            //abcd
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select trainnerID ,trainningTitle,count(*) as number from TrainningItemAPO where trainnerID='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDate+"' and trainningDate<='"+sqlEndDate+"' group by trainningTitle  " ;
            st.execute(str);

            //f
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainningitemfpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            //h
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainningitemhpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            //k
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainingresultkpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            //L
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainningitemlpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            //M
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainningitemmpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            //N
            str="insert into "+tmpTable+" (trainnerID ,trainningTitle ,trainningNumber) select id_TrainnerInfoPO ,trainningTitle,count(*) as number from trainningitemnpo where id_TrainnerInfoPO='"+sqlTrainnerId+"' and trainningDate>='"+sqlStartDateHIJ+"' and trainningDate<='"+sqlEndDateHIJ+"' group by trainningTitle  " ;
            st.execute(str);

            str="select trainnerID ,trainningTitle ,trainningNumber from "+tmpTable+" order by trainningTitle  " ;
            rs=st.executeQuery(str);
            String idStr,titleStr,numberStr;

            while(rs.next()){
                ItemDataType itemData = new ItemDataType();
                itemData.trainningTitle=rs.getString("trainningTitle");
                itemData.trainningCategory=ElfiiCommonUtil.getTrainningCategory(itemData.trainningTitle);
                itemData.trainningNumber=rs.getInt("trainningNumber");
                
                if(itemData.trainningTitle.startsWith("D")){
                	//训练D在数据库结果数据为实际数据的两倍，视觉和听觉是分别保存的
                	itemData.trainningNumber = itemData.trainningNumber/2;
                }
                
                dataList.add(itemData); 
            }
            str="drop table "+tmpTable;
            st.execute(str);
            long endTimeMillis=System.currentTimeMillis();
            //System.out.println("历史查询明细OK，Time:(1/1000) "+(endTimeMillis-startTimeMillis));
        } catch (Exception e) {System.out.print("ElfiiCommonhistoryItem.calcHistoryData() "+e+" "+str);}
    }

    public static long createRandomNumber(int baseNumber) {
        double d=Math.random() ;
        long k=1;
        for (int i=0; i<baseNumber; i++) {
            d*=10;
            k*=10;
        }
        if ((d+k/10)<k)
            d+=k/10;       //-不加k/10,出现位数不够的情况
        long kklong=(long) (d)%k ;
        if (kklong<0)
            kklong=0-kklong;
        return kklong ;
    }


}
